package com.loongtech.bi.advertisment.controller;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.loongtech.bi.advertisment.service.AdvUserDataService;
import com.loongtech.bi.manager.flow.HadoopQueryManager;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.core.util.Time;

/**
 * 
 * ClassName: AdvRoleDataAction
 * 
 * @Description: TODO 广告账号VIP统计
 * @author liuchen
 * @date 2017-6-22 上午11:40:41
 */
@Controller("advUserVipDataAction")
@Scope("view")
public class AdvUserVipDataAction extends BaseAdvAction {
	private static final long serialVersionUID = 1L;

	private String dateRadio = "7"; // 切换的天数：1=昨天。7=近7天。15=近15天。30=近30天，0=自选时间

	private Date dateStart = new Date(Time.getBeginningOfDay(Time.currentTime() - 7 * Time.DAY)); // 自选时间：开始时间

	private Date dateEnd = new Date(Time.getBeginningOfDay(Time.currentTime() - Time.DAY)); // 自选时间：结束时间

	private Date compareDate = new Date(Time.getBeginningOfDay(Time.currentTime() - Time.DAY)); // 前端传过来的查看时间

	@Resource(name = "advUserDataService")
	private AdvUserDataService service;

	@Autowired
	HadoopQueryManager hadoopQueryManager;

	@Autowired
	private SysLogManager sysLogManager;

	private List<ColumnModel> columns;

	private int maxviplevel = 8;

	private List<Object[]> result; // 结果List

	private List<Object[]> resultRate; // 结果List

	@PostConstruct
	public void init() {
		getVipColumns();
		try {
			search();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void getVipColumns() {
		columns = new ArrayList<ColumnModel>();
		maxviplevel = 0;
		try {
			maxviplevel = service.getVipLevel(1);
		} catch (Exception e) {
			maxviplevel = 10;
			e.printStackTrace();
		}
		columns.add(new ColumnModel("渠道", "0"));
		columns.add(new ColumnModel("新增账号", "1"));
		for (int i = 0; i <= maxviplevel; i++) {
			columns.add(new ColumnModel("VIP" + i, i + 2 + ""));
		}
	}

	public void search() throws Exception {
		sysLogManager.addLog(session.getUserName(), "市场数据分析 —— vip统计");

		String startDay = Time.getDateStr(new Date(Time.getBeginningOfDay(("0".equals(dateRadio) ? dateStart
				: new Date(Time.getBeginningOfDay(Time.currentTime() - (Integer.parseInt(dateRadio)) * Time.DAY)))
				.getTime()))); // 开始时间
		String endDay = Time.getDateStr(new Date(Time.getBeginningOfDay(("0".equals(dateRadio) ? dateEnd : new Date(
				Time.getBeginningOfDay(Time.currentTime() - Time.DAY))).getTime()))); // 结束时间

		result = new ArrayList<>();
		resultRate = new ArrayList<>();
		FacesContext context = FacesContext.getCurrentInstance();
		if (hasAgents == null || hasAgents.size() <= 0) {
			context.addMessage(null, new FacesMessage("提示", "此用户无任何代理商权限，请联系管理员配置!"));
			return;
		}
		if ((selectedAgent == null || selectedAgent.length <= 0) && !"admin".equals(session.getUserName())) {
			context.addMessage(null, new FacesMessage("提示", "请选择代理商!"));
			return;
		}
		System.out.println(compareDate);
		if (HadoopQueryManager.VISIT_QUEUE.offer("AdvUserVipDataAction")) {
			System.out.println("VISIT_QUEUE offer AdvUserVipDataAction ok!");
			StringBuffer sql = new StringBuffer();
			sql.append("select a.cname channelName,count(a.userid) newAccount  ");
			sql.append(getColumnSelect());
			sql.append("from  ");
			sql.append("(select min(nvl(bi.channelname,t.url))cname,userid from bi_adv_totalusercreate t ");
			sql.append("left join bi_advconfig bi on t.url = bi.id ");
			sql.append("where dt = (select max(dt) from bi_adv_totalusercreate) and t.createday >= '" + startDay
					+ "' and t.createday <= '" + endDay + "' ");
			if (selectedChannelName != null && selectedChannelName.length != 0) {
				sql.append("and channelName in (" + getParams(selectedChannelName) + ")");
			}
			if (selectedAgent != null && selectedAgent.length != 0) {
				sql.append("and agent in (" + getParams(selectedAgent) + ")");
			}
			if (selectedPlatform != null && selectedPlatform.length != 0) {
				sql.append("and platform in (" + getParams(selectedPlatform) + ")");
			}
			if (selectedPaytype != null && selectedPaytype.length != 0) {
				sql.append("and paytype in (" + getParams(selectedPaytype) + ")");
			}
			sql.append("group by userid)a ");
			sql.append("left join (select userid,max(viplevel)viplevel from roleinfo where dt = '"
					+ Time.getDateStr(compareDate) + "' group by userid)b on a.userid = b.userid ");
			sql.append("group by a.cname ");
			sql.append("order by newAccount ");

			Entry<List<String>, List<Object[]>> ret = hadoopQueryManager.executeSQL(sql.toString());
			if (null == ret || null == ret.getKey() || ret.getKey().isEmpty() || null == ret.getValue()) {
				context.addMessage(null, new FacesMessage("提示", "查询结果为空!"));
				return;
			}

			result = changeNum(ret.getValue());
		} else {
			System.out.println("VISIT_QUEUE offer AdvUserVipDataAction failed!");
			context.addMessage(null, new FacesMessage("提示", "当前系统正被访问，为保证服务器稳定，请稍后再试"));
			return;
		}

		DecimalFormat df = new DecimalFormat("0.000");
		for (Object[] o : result) {
			Object[] orate = new Object[o.length];
			for (int i = 0; i < o.length; i++) {
				if (i < 2) {
					orate[i] = o[i];
				} else {
					orate[i] = String.valueOf(df.format(Float.valueOf(String.valueOf(o[i])) / Float.valueOf(String.valueOf(o[1]))));
				}
			}
			resultRate.add(orate);
		}

	}

	private List<Object[]> changeNum(List<Object[]> re) {
		List<Object[]> r = new ArrayList<Object[]>();
		for (Object[] o : re) {
			Object[] oi = new Object[o.length];
			for (int i = 0; i < o.length; i++) {
				if (i < 1) {
					oi[i] = o[i];
				} else {
					oi[i] = Integer.valueOf(((String)o[i]));
				}
			}
			r.add(oi);
		}
		return r;
	}

	private String getColumnSelect() {
		StringBuilder s = new StringBuilder();
		for (int i = 0; i <= maxviplevel; i++) {
			s.append(" ,count(case when b.viplevel = " + i + " then a.userid  end) as v" + i + " ");
		}
		return s.toString();
	}

	private String getParams(String[] param) throws Exception {
		StringBuilder s = new StringBuilder();
		for (String str : param) {
			s.append("'" + str + "',");
		}
		return s.substring(0, s.length() - 1);
	}

	public List<Object[]> getResult() {
		return result;
	}

	public void setResult(List<Object[]> result) {
		this.result = result;
	}

	public List<Object[]> getResultRate() {
		return resultRate;
	}

	public void setResultRate(List<Object[]> resultRate) {
		this.resultRate = resultRate;
	}

	public String getDateRadio() {
		return dateRadio;
	}

	public void setDateRadio(String dateRadio) {
		this.dateRadio = dateRadio;
	}

	public Date getDateStart() {
		return dateStart;
	}

	public void setDateStart(Date dateStart) {
		this.dateStart = dateStart;
	}

	public Date getDateEnd() {
		return dateEnd;
	}

	public void setDateEnd(Date dateEnd) {
		this.dateEnd = dateEnd;
	}

	public List<ColumnModel> getColumns() {
		return columns;
	}

	public void setColumns(List<ColumnModel> columns) {
		this.columns = columns;
	}

	public Date getCompareDate() {
		return compareDate;
	}

	public void setCompareDate(Date compareDate) {
		this.compareDate = compareDate;
	}

	public class ColumnModel implements Serializable {

		private static final long serialVersionUID = 1L;
		private String header;
		private String property;

		public ColumnModel(String header, String property) {
			this.header = header;
			this.property = property;
		}

		public String getHeader() {
			return header;
		}

		public String getProperty() {
			return property;
		}
	}
}
